package com.suieqian.aspect;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * 使用@Aspect拦截请求日志
 * filter.logFile 里使用 file拦截日志
 * @author win10
 */
@Aspect
@Component
@Order(1)
@Slf4j
public class LogRecordAspect {
    private final static String POST = "POST";
    private final static String GET = "GET";


    /**
     * 切点
     */
    @Pointcut("execution(* com.suieqian.controller.*..*(..))")
    private void pointcut() {
    }

    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        long start = System.currentTimeMillis();
        String requestId = start + getRandom();

        log.info("请求开始requestId:" + requestId + "===地址:" + request.getRequestURL().toString());
        String method = request.getMethod();
        String queryString = request.getQueryString();
        Object[] args = pjp.getArgs();
        String token = request.getHeader("token");
        log.info("请求开始requestId:" + requestId + "===token:" + token);
        try {
            //获取请求参数集合并进行遍历拼接
            if (args.length > 0) {
                if (POST.equals(method)) {
                    for (Object arg : args) {
                        if (!(arg instanceof BeanPropertyBindingResult)) {
                            log.info("请求开始requestId:" + requestId + "===POST参数:" + JSONUtil.toJsonStr(arg));
                        }
                    }
                } else if (GET.equals(method)) {
                    //restful 风格无需打印参数
                    log.info("请求开始requestId:" + requestId + "===GET参数:" + queryString);
                }
            }
        } catch (Exception e) {
            log.error("对象转换参数错误", e);
        }

        Object result = null;
        try {
            result = pjp.proceed();
            long end = System.currentTimeMillis();
            log.info("请求结束requestId:" + requestId + "==用时:" + (end - start) + "ms===返回值:" + JSONUtil.toJsonStr(result));
        } catch (Exception e) {
            log.error("对象转换返回值错误", e);
            throw e;
        }
        return result;
    }

    //获取随机数
    public String getRandom() {
        Random ran = new Random();
        int random = ran.nextInt(10000);
        return String.valueOf(random);
    }
}
